const util = require('util');
const exec = util.promisify(require('child_process').exec);
const { execSync } = require('child_process');
const chalk = require('chalk');
const { boxen } = require('./uiUtil');
const currentVersion = require('../package.json').version;

const { accessSync, constants } = require('fs');

// @ts-ignore
const timmer = (duration) => new Promise((resolve) => setTimeout(resolve, duration));

const getVersion = () => {
  const cmd = 'npm view @chanjet/cjet-cmd version  --registry=https://registry-npm.rd.chanjet.com';
  return Promise.race([exec(cmd), timmer(5000)]);
};
const useYarn = async () => {
  try {
    const cmd = 'ls -l $(which cdts)';
    let res = (await exec(cmd)).stdout;
    const isInstallByYarn = /\/yarn\//.test(res);
    return isInstallByYarn;
  } catch (err) {
    return false;
  }
};


const checkIfNeedSudo = async (testCmd = 'which cdts') => {
  try {
    const filepath = (await exec(testCmd)).stdout.replace(/\n/g, '');
    accessSync(filepath, constants.R_OK | constants.W_OK);
    return false;
  } catch (err) {
    return true;
  }
};

async function test() {
  console.log(chalk.cyan('new version ?'), (await getVersion()).stdout.match(/^\d+\.\d+\.\d+$/m)[0]);
  console.log(chalk.cyan('need sudo  ?'), await checkIfNeedSudo() ? 'yes' : 'no');
  console.log(chalk.cyan('use  yarn  ?'), await useYarn() ? 'yes' : 'no');
}

test()

const autoUpgrade = async () => {
  try {
    let pkgInfo = await getVersion();

    if (!pkgInfo) {
      console.warn('获取cjet-cmd版本号超时');
      return;
    }

    let matcher = pkgInfo.stdout.match(/^\d+\.\d+\.\d+$/m);

    let latestVersion;

    if (matcher) {
      latestVersion = matcher[0];
    }

    if (Number(latestVersion.replace(/\./, '')) > Number(currentVersion.replace(/\./, ''))) {

      const upgradeTip = [
        'npm i -g @chanjet/cjet-cmd --registry=https://registry-npm.rd.chanjet.com',
        `yarn global add @chanjet/cjet-cmd --registry=https://registry-npm.rd.chanjet.com`
      ].join('\n  ')

      const boxCentent = boxen([
        `cjet-cmd 自动升级 from ${chalk.cyanBright(currentVersion)} to ${chalk.cyanBright(latestVersion)}`,
        `如果自动升级失败，请尝试手动更新`,
        `${chalk.green(upgradeTip)}`
      ])

      console.log(boxCentent);

      const useSudo = (await checkIfNeedSudo) ? 'sudo ' : '';

      if (await useYarn()) {
        execSync(useSudo + 'yarn global add @chanjet/cjet-cmd --registry=https://registry-npm.rd.chanjet.com', {
          stdio: 'inherit',
        });
      } else {
        execSync(useSudo + 'npm i -g @chanjet/cjet-cmd --registry=https://registry-npm.rd.chanjet.com', {
          stdio: 'inherit',
        });
      }
      console.log(chalk.green('\n 升级成功!!! \n'));
    }
  } catch (err) {
    return currentVersion;
  }
};

module.exports = { autoUpgrade };
